﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using STS.Model;
using System;

namespace STS.ViewModel
{
    public class OrganViewModel : BaseViewModel
    {
        private ObservableCollection<Organ> _organItems;
        public ObservableCollection<Organ> OrganItems
        {
            get
            {
                if (_organItems == null)
                {
                    _organItems = new ObservableCollection<Organ>();
                }
                return _organItems;
            }
            set
            {
                _organItems = value;
                NotifyPropertyChanged("OrganItems");
            }
        }

        public void FindOrganItems()
        {
            var organDB = from organ in ModelInstance.DataContext.OrganItems
                           select organ;
            OrganItems = new ObservableCollection<Organ>(organDB);
            Debug.WriteLine("Znalazłem Organy, size = " + OrganItems.Count);
        }

        public Organ FindOrganByIdOrgan(int organId)
        {
            var organDB = from organ in ModelInstance.DataContext.OrganItems
                           where organ.IdOrganu == organId
                           select organ;
            return organDB.SingleOrDefault<Organ>();
        }

        public void UpdateOrgan(Organ updateOrgan)
        {
            Organ old = FindOrganByIdOrgan(updateOrgan.IdOrganu);
            SetEntityPropertities(ref old, updateOrgan);
            SaveChangesToDB();
        }

        public void AddOrgan(Organ organ)
        {
            ModelInstance.DataContext.OrganItems.InsertOnSubmit(organ);
            SaveChangesToDB();
            OrganItems.Add(organ);
        }

        public void RemoveOrgan(Organ organ)
        {
            OrganItems.Remove(organ);
            ModelInstance.DataContext.OrganItems.DeleteOnSubmit(organ);
            SaveChangesToDB();
        }

        public void RemoveAllOrgan()
        {
            var organDB = from organ in ModelInstance.DataContext.OrganItems
                           select organ;

            foreach (Organ _organ in organDB)
            {
                ModelInstance.DataContext.OrganItems.DeleteOnSubmit(_organ);
            }

            try
            {
                SaveChangesToDB();
                OrganItems.Clear();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }

    }
}
